const EtherToken = require('../common/contract/EtherToken');
const SmartToken = require('../common/contract/SmartToken');
const BancorConverter = require('../common/contract/BancorConverter');
const curl = require("../common/curl");


const bancorPriceDao = require("../common/dao/bancor_price");
const bancorPricesDao = require("../common/dao/bancor_prices");
const bancorCurrencyDao = require("../common/dao/bancor_currency");


async function getCurrencyList() {
    let currencyList = await curl.curlGet({
        url: "http://fomo.abcblockchain.io/api/publics/getCurrencyList",
    });

    let localList = await bancorCurrencyDao.currencyList({});
    let names = [];
    for (let i in localList) {
        names.push(localList[i].currency_name);
    }
    let list = currencyList.data;
    for (let i in list) {
        if (names.indexOf(list[i].currency_name) < 0) {
            await bancorCurrencyDao.currencyAdd({
                currency_name: list[i].currency_name,
                currency_mark: list[i].currency_mark,
                bcv_address: list[i].bcv_address,
                contract_address: list[i].contract_address
            });
        }
    }
    return list;
}

async function getPrice(address) {
    let converterAddr = await SmartToken.owner(address);
    // console.log(converterAddr);

    let smart_token_balance = await SmartToken.totalSupply(address);
    // console.log(smart_token_balance);

    let connectBalance = await EtherToken.balanceOf(converterAddr);
    // console.log(connectBalance);

    let connector = await BancorConverter.connectors(converterAddr, EtherToken.address());
    let cw = connector.weight / 1000000;
    // console.log(connector);

    return connectBalance / (cw * smart_token_balance);
}


module.exports = {
    async syncPrice() {
        try {
            // 1.查询同步到的位置
            let currencyList = await getCurrencyList();
            for (let i in currencyList) {
                let address = currencyList[i].contract_address;
                let price = await getPrice(address);
                let res = await bancorPriceDao.bancorPriceList({
                    contract: address
                });
                if (res.length == 0) {
                    await bancorPriceDao.bancorPriceAdd({
                        contract: address,
                        price: price
                    });
                } else {
                    await bancorPriceDao.bancorPriceUpdate({contract: address}, {
                        price: price
                    });
                }
                console.log({
                    contract: address,
                    price: price
                });
                await bancorPricesDao.bancorPricesAdd({
                    contract: address,
                    price: price
                });
            }
        } catch (e) {
            console.log(e);
        }

    }
};